package com.example.wangda.smartparking;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;

import com.ant.liao.GifView;
import com.chinamobile.iot.onenet.mqtt.MqttCallBack;
import com.chinamobile.iot.onenet.mqtt.MqttClient;
import com.chinamobile.iot.onenet.mqtt.MqttConnectOptions;
import com.chinamobile.iot.onenet.mqtt.protocol.MqttConnAck;
import com.chinamobile.iot.onenet.mqtt.protocol.MqttMessage;
import com.chinamobile.iot.onenet.mqtt.protocol.MqttPublish;
import com.chinamobile.iot.onenet.mqtt.protocol.MqttSubAck;
import com.chinamobile.iot.onenet.mqtt.protocol.MqttSubscribe;
import com.chinamobile.iot.onenet.mqtt.protocol.imp.Type;
import static android.content.ContentValues.TAG;
import static com.chinamobile.iot.onenet.mqtt.protocol.imp.QoS.AT_MOST_ONCE;


public class SimulaActivity extends Activity{
    private GifView gif;
    private boolean gif_playSta = false;
    private Button btn_reserve;
    private Button btn_location;
    private Button btn_clear;
    private Button btn_navi;
    private TextView textView_space;
    private TextView textViewReservaParking;
    int parkingNum=0;
    int carportSta=0;
    int screenWidth=0;
    int screenHeight=0;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_simula);
            MqttInit(SimulaActivity.this);

            btn_reserve = (Button)findViewById(R.id.btn_reserve);
            btn_location = (Button)findViewById(R.id.btn_location);
            btn_clear = (Button)findViewById(R.id.btn_clear);
            btn_navi = (Button)findViewById(R.id.btn_find);
            textView_space = (TextView)findViewById(R.id.textView_space);
            textViewReservaParking = (TextView)findViewById(R.id.textViewReservaParking);
            /*获取屏幕分辨率 适配gif*/
            WindowManager windowManager = getWindowManager();
            Display display = windowManager.getDefaultDisplay();
            screenWidth  = display.getWidth();
            screenHeight = display.getHeight();
            btn_reserve.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(gif_playSta != true) {
                        gif.setGifImage(R.drawable.reserve);
                        gif.setShowDimension(screenWidth,screenHeight/2);
                        gif_playSta = true;
                        textViewReservaParking.setText(""+ reservaParking());
                        MqttPublishMessage(""+ reservaParking());
                        new AlertDialog.Builder(SimulaActivity.this).setTitle("提示")
                                .setMessage("即将开始演示")
                                .setPositiveButton("开始", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        gif.showAnimation();
                                    }
                                }).show();
                    }else{
                        new AlertDialog.Builder(SimulaActivity.this).setTitle("提示")
                                .setMessage("请您先点击动图区域，暂停动图播放后再切换功能！")
                                .setPositiveButton("好的！", null).show();
                    }
                }
            });
            btn_location.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(gif_playSta != true) {
                        gif.setGifImage(R.drawable.location);
                        gif.setShowDimension(screenWidth,screenHeight/2);
                        gif_playSta = true;
                        new AlertDialog.Builder(SimulaActivity.this).setTitle("提示")
                                .setMessage("即将开始演示")
                                .setPositiveButton("开始", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        gif.showAnimation();
                                    }
                                }).show();
                    }else {
                        new AlertDialog.Builder(SimulaActivity.this).setTitle("提示")
                                .setMessage("请您先点击动图区域，暂停动图播放后再切换功能！")
                                .setPositiveButton("好的！", null).show();
                    }
                }
            });
            btn_clear.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                }
            });
            btn_navi.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(gif_playSta != true) {
                        gif.setGifImage(R.drawable.find);
                        gif.setShowDimension(screenWidth,screenHeight/2);
                        gif_playSta = true;
                        new AlertDialog.Builder(SimulaActivity.this).setTitle("提示")
                                .setMessage("即将开始演示")
                                .setPositiveButton("开始", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        gif.showAnimation();
                                    }
                                }).show();
                    }else{
                        new AlertDialog.Builder(SimulaActivity.this).setTitle("提示")
                                .setMessage("请您先点击动图区域，暂停动图播放后再切换功能！")
                                .setPositiveButton("好的！", null).show();
                    }
                }
            });

            gif = (GifView)findViewById(R.id.gif1);
            gif.setGifImageType(GifView.GifImageType.COVER);
            gif.setShowDimension(1200,1000);
            gif.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(gif_playSta){
                        gif.showCover();
                        gif_playSta = false;
                    }else{
                        gif.showAnimation();
                        gif_playSta = true;
                    }
                }
            });
        }
        /***************************MQTT SERVER***********************/
        public void MqttInit(Context context) {
            String apikey = "57khJ52JlHjPTydT6en=ru5=45Y=";
            String clientId = "23253479";
            String product_id = "113096";
            // 1、初始化SDK
            MqttClient.initialize(context, "183.230.40.39", 6002, clientId, product_id, apikey);
            // 2、设置接收响应的回调
            MqttClient.getInstance().setCallBack(callBack);
            // 3、设置连接属性(eg:心跳包。选填,可以不设置,调用connect()方法)
            MqttConnectOptions connectOptions = new MqttConnectOptions();
            connectOptions.setCleanSession(true);
            connectOptions.setKeepAlive(200);
            connectOptions.setWill(false);
            connectOptions.setWillQoS(AT_MOST_ONCE);
            connectOptions.setWillRetain(false);
            // 4、建立TCP连接
            MqttClient.getInstance().connect(connectOptions);
        }
    /*连接MQTT服务器*/
    public void UserConnect(Context context)
    {
        MqttClient.getInstance().disconnect();

        String apikey = "Yd9VgMbOlERW5qX7MtQnSGk5kfU=";
        String clientId = "19946427";
        String product_id = "99461";
        // 1、初始化SDK
        MqttClient.initialize(context, "183.230.40.39", 6002, clientId, product_id, apikey);
        // 2、设置接收响应的回调
        MqttClient.getInstance().setCallBack(callBack);
        MqttConnectOptions connectOptions = new MqttConnectOptions();
        connectOptions.setCleanSession(true);
        connectOptions.setKeepAlive(200);
        connectOptions.setWill(false);
        connectOptions.setWillQoS(AT_MOST_ONCE);
        connectOptions.setWillRetain(false);
        // 4、建立TCP连接
        MqttClient.getInstance().connect(connectOptions);
    }
        /*断开连接MQTT服务器*/
        public void UserUnconnect()
        {
            MqttClient.getInstance().disconnect();
        }
        /*创建回调函数（用来接收MQTT消息，继承CallBack接口）*/
        private MqttCallBack callBack = new MqttCallBack() {
            @Override
            public void messageArrived(MqttMessage msg) {
                //连接响应
                if (msg.getMqttHeader().getType() == Type.CONNACK) {
                    MqttConnAck mqttConnAck = (MqttConnAck) msg;
                    //透传消息 server->client
                    MqttClient.getInstance().subscribe(new MqttSubscribe("android", AT_MOST_ONCE));
                    Log.d(TAG, "MQTT Connect");
                } else if (msg.getMqttHeader().getType() == Type.PUBLISH) {
                    MqttPublish mqttPublish = (MqttPublish) msg;
                    String topic = mqttPublish.getTopicName();
                    int msgId = mqttPublish.getMsgID();
                    byte[] data = mqttPublish.getData();
                    MqttRecvDateHandle(topic, msgId, data);
                    Log.d(TAG, "MQTT PUBLISH");
                    //订阅响应
                } else if (msg.getMqttHeader().getType() == Type.SUBACK) {
                    MqttSubAck mqttSubAck = (MqttSubAck) msg;
                    Log.d(TAG, "MQTT SUBACK");
                    //心跳响应
                } else if (msg.getMqttHeader().getType() == Type.PINGRESP) {
                    Log.d(TAG, "MQTT PINGRESP");
                    //发布响应QOS1
                } else if (msg.getMqttHeader().getType() == Type.PUBACK) {
                    //发布响应QOS2
                } else if (msg.getMqttHeader().getType() == Type.PUBCOMP) {

                }
            }
            //网络异常导致的断开
            @Override
            public void connectionLost(Exception e) {
                UserConnect(SimulaActivity.this);
                Log.d(TAG, "MQTT 网络异常导致的断开");
            }
            //连接断开
            @Override
            public void disconnect() {
                UserConnect(SimulaActivity.this);
                Log.d(TAG, "MQTT 连接断开");
            }
        };
        /*MQTT发布消息*/
        public void MqttPublishMessage(String str)
        {
            MqttPublish user_publish = new MqttPublish("parking",str.getBytes(),AT_MOST_ONCE);
            MqttClient.getInstance().sendMsg(user_publish);
        }

        /*查询剩余车位*/
        public int readRemainCarport()
        {
            return parkingNum;
        }
        /*查询车位状态*/
        public int readCarportSta()
        {
            return carportSta;
        }
    /*预约车位*/
        public int reservaParking()
        {
            for(int for_i=0; for_i<8;for_i++){
                if(((carportSta>>for_i)&0x01) == 0x01)
                {
                    return for_i+1;
                }
            }
            return 0;
        }
    /*处理接收消息*/
    private void MqttRecvDateHandle(String topic, int msgId, byte[] data)
    {
        String strData = new String(data).trim();
        if(!topic.equals("android"))return;
        carportSta = Integer.parseInt(strData);
        Log.d(TAG, "int is" + carportSta);
        parkingNum = 0;
        for(int for_i=0; for_i<8;for_i++){
            if(((carportSta>>for_i)&0x01) == 0x01)
            {
                parkingNum++;
            }
            else
            {
                Log.d(TAG, "车位 " + for_i + "被占");
            }
        }
        textView_space.setText("" + readRemainCarport());
        Log.d(TAG, "parkingNum is " + parkingNum);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        UserUnconnect();
    }
}

